<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary"
                  @click="handleExport">导出</a-button>
        <a-button type="primary"
                  @click="handleCreate">新增</a-button>
        <Popconfirm title="确定要删除吗"
                    ok-text="确认"
                    cancel-text="取消"
                    @confirm="handleBatchDeletUser">
          <a-button type="primary">批量删除</a-button>
        </Popconfirm>
      </template>
      <template #startTime="{ record }"> {{ record.startTime }}~{{record.endTime}}</template>
      <template #action="{ record, column }">
        <TableAction :actions="createActions(record, column)" />
      </template>
      <template #number="{ record, column }">
        <TableAction :actions="createnumber(record, column)" />
      </template>

    </BasicTable>

    <Modal @register="registerModal"
           @success="handleSuccess" />
    <Mod @register="register"
         @success="handleSuccess" />
    <!-- 驳回 -->
    <ApplicationModal @register="registerModal2"
                      @successModel="handleSuccess" />
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref } from 'vue';
import {
  ActionItem,
  BasicColumn,
  BasicTable,
  EditRecordRow,
  FormSchema,
  useTable,
  TableAction,
} from '/@/components/Table';

import {
  ListApi,
  ChangeStatusApi,
  ChangeRecommendApi,
  DeleteApi,
  ExportApi,
} from '/@/api/activityAdmin';
import {
  onlineStatusType,
  Recommended,
  authorizeStatusType,
  publisher,
  activityForm,
} from '/@/assets/dic';
import formatDic from '/@/utils/formatDic';
import { UserItem } from '/@/api/activityAdmin/userModel';
import Modal from './modal.vue';
import Mod from './mod.vue';
import { useModal } from '/@/components/Modal';
import { Popconfirm } from 'ant-design-vue';
import ApplicationModal from './applicationModal.vue';
import { downloadFile } from '/@/utils/file/download';
import { GetcitylistApi } from '/@/api/activityAdmin/index';
const columns: BasicColumn[] = [
  {
    title: '活动标题',
    dataIndex: 'title',
  },
  {
    title: '活动形式',
    dataIndex: 'mode',
    format: formatDic(onlineStatusType),
  },
  {
    title: '发布方',
    dataIndex: 'publisher',
    format: formatDic(publisher),
  },
  {
    title: '发布者昵称',
    dataIndex: 'nickName',
  },
  {
    title: '授权更改首图',
    dataIndex: 'authorize',
    format: formatDic(authorizeStatusType),
  },
  {
    width: 280,
    title: '活动时间',
    dataIndex: 'startTime',
    slots: { customRender: 'startTime' },
  },
  {
    title: '区域',
    dataIndex: 'bigareaForm',
  },
  {
    title: '发布时间',
    dataIndex: 'createTime',
  },
  {
    title: '状态',
    dataIndex: 'isUse',
    format: formatDic(activityForm),
  },
  {
    title: '是否推荐',
    dataIndex: 'recommend',
    format: formatDic(Recommended),
  },
  {
    title: '报名人数',
    dataIndex: 'number',
    slots: { customRender: 'number' },
  },
];

const colProps = {
  span: 6,
};
const schemas: FormSchema[] = [
  {
    label: '活动标题：',
    field: 'title',
    component: 'Input',
    colProps,
  },
  {
    label: '发布方',
    field: 'publisher',
    component: 'Select',
    componentProps: {
      options: publisher,
    },
    colProps,
  },
  {
    label: '发布者昵称：',
    field: 'nickName',
    component: 'Input',
    colProps,
  },
  {
    label: '状态：',
    field: 'isUse',
    component: 'Select',
    componentProps: {
      options: activityForm,
    },
    colProps,
  },
  {
    label: '是否推荐：',
    field: 'recommend',
    component: 'Select',
    componentProps: {
      options: Recommended,
    },
    colProps,
  },
  {
    label: '授权更改首图',
    field: 'authorize',
    component: 'Select',
    componentProps: {
      options: authorizeStatusType,
    },
    colProps,
  },
  {
    label: '区域：',
    field: 'city',
    component: 'AreaCascader',
    colProps,
  },
  {
    field: 'createTime',
    label: '时间：',
    component: 'RangePicker',
    componentProps: {
      valueFormat: 'YYYY-MM-DD',
    },
    colProps,
  },
];

export default defineComponent({
  name: 'AverageUser',
  components: {
    BasicTable,
    TableAction,
    Modal,
    Mod,
    Popconfirm,
    ApplicationModal,
  },
  setup() {
    let formStatus = reactive({});
    const citylist = ref<AreaList[]>([]);
    // const selectedRowKeys = ref<string[]>([]);
    const [registerModal, { openModal }] = useModal();
    const [register, { openModal: openModal1 }] = useModal();
    const [registerModal2, { openModal: openModal2 }] = useModal();
    const [registerTable, { reload, getSelectRows }] = useTable({
      api: ListApi,
      useSearchForm: true,
      rowSelection: {
        type: 'checkbox',
      },
      columns,
      formConfig: {
        schemas,
        labelWidth: 100,
      },
      beforeFetch(params) {
        if (Array.isArray(params.city)) {
          params.area = params.city[1];
          params.city = params.city[0];
        }
        if (Array.isArray(params.createTime)) {
          params.createTime = params.createTime.join('~');
        }
      },
      handleSearchInfoFn(params) {
        if (Array.isArray(params.city)) {
          params.area = params.city[1];
          params.city = params.city[0];
        }
        if (Array.isArray(params.createTime)) {
          params.createTime = params.createTime.join('~');
        }
        formStatus = params;
      },
      afterFetch(record) {
        record.forEach((element) => {
          const cityItem = citylist.value.filter((item) => {
            return item.id == element.city;
          });

          if (cityItem.length > 0) {
            element.bigareaForm = `${cityItem[0].city || ''}-${element.area || ''}`;
          }
        });
      },
      actionColumn: {
        width: 230,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
      },
    });

    function Getcitylist() {
      GetcitylistApi().then((res) => {
        if (res.code == 200) {
          citylist.value = res.data;
        }
      });
    }
    Getcitylist();
    function handleCreate() {
      console.log('点击了新增');
      openModal(true, {
        isUpdate: false,
      });
    }

    function handleSuccess() {
      reload();
    }
    // 改变用户的使用状态
    // function handleChangeStatus(record: UserItem) {
    //   record.status = record.status === 0 ? 1 : 0;
    //   console.log( record.status,' record.status')
    //   ChangeStatusApi(record).then((_) => {
    //     reload();
    //   });
    // }

    function handleChangeStatus(record: UserItem) {
      record.isUse = record.isUse === 0 || record.isUse === 2 ? 1 : 0;
      ChangeStatusApi(record).then((_) => {
        reload();
      });
    }
    // 是否推荐
    function handleChangeRecommend(record: UserItem) {
      record.recommend = record.recommend === 0 ? 1 : 0;
      ChangeRecommendApi(record).then((_) => {
        reload();
      });
    }
    // 删除用户
    function handleDeletUser(ids: number | number[]) {
      console.log(ids);
      DeleteApi(ids).then((_) => {
        reload();
      });
    }
    // 拿到需要批量删除的id
    function handleBatchDeletUser() {
      const selectRows = getSelectRows();
      const ids = selectRows.map((item) => item.id);

      handleDeletUser(ids);
      // DeleteApi(ids).then((_) => {
      //   // reload();
      // });
    }
    function createnumber(record: EditRecordRow, _: BasicColumn): ActionItem[] {
      return [
        {
          label: `${record.number}`,
          color: 'rgba(70, 144, 228, 1)',
          onClick() {
            openModal1(true, {
              record,
              isUpdate: true,
            });
          },
        },
      ];
    }
    function createActions(record: EditRecordRow, _: BasicColumn): ActionItem[] {
      // 使用状态（0：已下线；1：已上线；2：待审核；3：已驳回）
      if (record.isUse == 2) {
        return [
          {
            label: record.isUse === 1 ? (record.recommend === 1 ? '推荐' : '取消推荐') : '',

            onClick: handleChangeRecommend.bind(null, record as UserItem),
          },
          {
            label: '编辑',
            color: 'success',
            onClick() {
              openModal(true, {
                record,
                isUpdate: true,
              });
            },
          },
          {
            // label: record.status === 0 ? '上线' : '下线',
            label: '上线 ',
            onClick: handleChangeStatus.bind(null, record as UserItem),
          },
          {
            label: '驳回',
            color: 'error',
            onClick() {
              openModal2(true, {
                record,
              });
            },
          },

          {
            label: '删除',
            color: 'error',
            popConfirm: {
              title: '确定要删除吗！',
              confirm() {
                handleDeletUser(record.id);
              },
            },
          },
        ];
      } else if (record.isUse == 3) {
        return [
          {
            label: '编辑',
            color: 'success',
            onClick() {
              openModal(true, {
                record,
                isUpdate: true,
              });
            },
          },
          {
            label: '删除',
            color: 'error',
            popConfirm: {
              title: '确定要删除吗！',
              confirm() {
                handleDeletUser(record.id);
              },
            },
          },
        ];
      } else {
        return [
          {
            label: record.isUse === 1 ? (record.recommend === 1 ? '推荐' : '取消推荐') : '',

            onClick: handleChangeRecommend.bind(null, record as UserItem),
          },
          {
            label: '编辑',
            color: 'success',
            onClick() {
              openModal(true, {
                record,
                isUpdate: true,
              });
            },
          },
          {
            label: record.isUse === 0 ? '上线' : '下线',
            onClick: handleChangeStatus.bind(null, record as UserItem),
          },

          {
            label: '删除',
            color: 'error',
            popConfirm: {
              title: '确定要删除吗！',
              confirm() {
                handleDeletUser(record.id);
              },
            },
          },
        ];
      }
    }
    // 导出
    async function handleExport() {
      const res = await ExportApi(formStatus);
      downloadFile(res.msg);
    }
    return {
      registerTable,
      createActions,
      handleBatchDeletUser,
      registerModal,
      register,
      handleSuccess,
      handleCreate,
      createnumber,
      registerModal2,
      handleExport,
    };
  },
});
</script>
<style lang="less" scoped></style>
